#!env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/5/10 11:53
# @Author  : WuLiang
# @FileName: before_build.py
# @Software: PyCharm

import json
import sys

ALIGN = "32"
image_header_size = "0x100"

def json2macro(rfile_path,wfile_path):
    result = dict()
    try:
        with open(rfile_path,'r',encoding='utf-8') as f:
            result = json.loads(f.read())
    except Exception as e:
        pass

    with open(wfile_path, "w+") as f:
        file_v = wfile_path.split("\\")[-1].replace(".h","").upper()
        startcomment = "#ifndef __" + file_v + "__\n#define __" + file_v + "__\n\n\n//flash partition map,it's generated by the script based on the json file <flash_partition_table.json>\n"
        f.writelines(startcomment)
        
        count = 0
        last_name1 = ""
        last_name2 = ""
        for key,value in result.items():
            try:
                if key not in ["Warning1","Warning2"]:
                    for i in value:
                        name1 = i['partition_type'] + "_SPACE_OFFSET"
                        name2 = i['partition_type'] + "_SPACE_SIZE"

                        temp1 = "".join(["#define ",  format(name1," <"+ALIGN),  " (",  i['start_addr'],  ")"])
                        temp2 = "".join(["#define ",  format(name2," <"+ALIGN),  " (1024*",  str(i['size_KB']),  ')'])

                        f.writelines("\n"+temp1+"\n")
                        f.writelines(temp2+"\n")
                        
                        if (count > 0):
                            temp3 = "".join(["#if (", name1, " < (", last_name1, " + ", last_name2, "))"])
                            f.writelines(temp3 + "\n")
                            f.writelines("  #error \"flash partition overlap,please check <flash_partition_table.json>!!!\"\n")
                            f.writelines("#endif\n")
                            
                        count = count + 1
                        last_name1 = name1
                        last_name2 = name2
            except Exception as e:
                print(e)

        
        temp = "".join(["\n\n#define ",  format("IMAGE_HEADER_SIZE"," <"+ALIGN),  " ",  "("+image_header_size+")"])
        f.writelines(temp)
        endcommont = "\n\n#endif /* __" + file_v + "__ */\n\n"
        f.writelines(endcommont)


def main(argv):
    arg_count = len(sys.argv)
    # print("arg count = ", arg_count)
    # print(sys.argv[1])
    # print(sys.argv[2])
    
    if arg_count == 3:
        rfile_path = sys.argv[1]
        wfile_path = sys.argv[2]
        json2macro(rfile_path, wfile_path)
    else:
        assert arg_count == 3


if __name__ == "__main__":
    version = sys.version.split(' ')[0]
    if version < str(3):
        print("pyhton version is too low,please install python3 !\n")
        assert version < str(3)
    else:
        main(sys.argv)




